#include "CResourceManager.h"

CResourceManager::CResourceManager(SGameComponents &gamePointers) 
	: m_sGamePointers(gamePointers), m_vResPathes(ER_COUNT, ""),
	m_cpResPathesFile("resources.xml")
{
	m_pDevice = (IrrlichtDevice *)m_sGamePointers.GameDevice;
	m_pFileSystem = m_pDevice->getFileSystem();

	//if(!m_cpResoucesPathesFile)
	getResPathes();

	m_pResourcePointer = new void *[ER_COUNT];
}

bool CResourceManager::getResPathes()
{
	IAttributes *pathes = m_pFileSystem->createEmptyAttributes();
	IXMLReader *resourcesPathesReader
		= m_pFileSystem->createXMLReader(m_cpResPathesFile);

	if(!resourcesPathesReader)
	{
		std::cout << "File not exist" << std::endl;
		return false;
	}
	else 
		std::cout << "File " << m_cpResPathesFile <<" was loaded" << std::endl;

	initResVariables();

	for(uint i = 0; i < ER_COUNT; i++)
		pathes->addString(m_pResVars[i], m_vResPathes[i]);

	pathes->read(resourcesPathesReader);

	return true;
}

void CResourceManager::initResVariables()
{
	m_pResVars = new c8 *[ER_COUNT]; 
	m_pResVars[ER_CONFIG_FILE] = "configFile";
	m_pResVars[ER_RECORDS_FILE] = "recordsFile";
	m_pResVars[ER_MAIN_MENU_SPRITE] = "mainMenuSprite";
	m_pResVars[ER_CURSOR_IMAGE] = "cursorImage";
	m_pResVars[ER_CLICK_SOUND] = "clickSound";
	m_pResVars[ER_BUTTON_SOUND] = "buttonSound";
	m_pResVars[ER_MAIN_MENU_SOUND] = "mainMenuSound";
	m_pResVars[ER_LEVELS_PATH] = "levelsPath";
	m_pResVars[ER_FLOOR_MESH] = "floorMesh";
	m_pResVars[ER_WALL_MESH] = "wallMesh";
	m_pResVars[ER_HERO_MESH] = "heroMesh";
	m_pResVars[ER_COIN_MESH] = "coinMesh";
}

void CResourceManager::loadingMeshes()
{
	ISceneManager *sceneManager = m_pDevice->getSceneManager();
	for(uint i = ER_FLOOR_MESH - 1; i < ER_COIN_MESH; i++)
		m_pResourcePointer[i] = sceneManager->getMesh(m_vResPathes[i]);

	sceneManager->drop();
}

IMesh *CResourceManager::getMeshPointer(EMeshResourcesID meshResource)
{
	if(meshResource >= ER_FLOOR_MESH || meshResource < ER_COIN_MESH)
		return (IMesh *)m_pResourcePointer[meshResource];

	return NULL;	
}

void CResourceManager::loadingTextures()
{
	IVideoDriver *videoDriver = m_pDevice->getVideoDriver();
	for(uint i = ER_MAIN_MENU_SPRITE - 1; i < ER_CURSOR_IMAGE; i++)
		m_pResourcePointer[i] = videoDriver->getTexture(m_vResPathes[i]);

	videoDriver->drop();
}

ITexture * CResourceManager::getTexturePointer(ETextureResourcesID textureResource)
{
	if(textureResource >= ER_MAIN_MENU_SPRITE 
		|| textureResource < ER_CURSOR_IMAGE)
		return (ITexture *)m_pResourcePointer[textureResource];

	return NULL;
}

void CResourceManager::loadingAllRes()
{
	loadingMeshes();
	loadingTextures();
}

CResourceManager::~CResourceManager()
{

}

